var newBgImg='',bj='';
$(function () {
    //座标输入错误提示
    function toobarErr(el, pos, text){
        el.css({
            left: pos.left + 3 + "px",
            top: pos.top + 10 + "px"
        }).text(text).attr("data-lock", "true").show();
        setTimeout(function(){
            el.hide();
        }, 3000);
    }
    //座标输入设置
    function toolbarSet(that, e){
        var type = that.attr("data-type");//当前元素设置类型
        var thisPos = that.position();//当前元素位移
        var val = that.val().trim();//清空输入内容的容格
        var errEl = $(".toolbar-error");//错误提示框
        var id = errEl.attr("data-id");//错误提示的id
        var data = Model.define.elements[id].props;//当前设置元素的位移宽高层级
        if(thisPos.left < 100){
            thisPos = that.next().position();
        }
        $(".computer-top-nav").hide();
        thisPos.left += 2;
        thisPos.top += 13;
        if(parseFloat(val) != 0 &&!!!parseFloat(val)){
            toobarErr(errEl, thisPos, "请输入整数！");
            IS_MOVE = false;
            that.focus();
            Utils.selectShape(id, false, "toolbar");
            return false;
        }
        if(!validateIntNumber(val)){
            toobarErr(errEl, thisPos, "请输入整数！");
            IS_MOVE=false;
            that.focus();
            Utils.selectShape(id, false, "toolbar");
            return false;
        }
        switch(type){
            case "x":
                val = parseInt(val);
                if(Model.define.page.width <  data.w + val){
                    toobarErr(errEl, thisPos, "元素横向坐标加宽度不得超编辑器大小！");
                    that.focus();
                    IS_MOVE=false;
                    Utils.selectShape(id, false, "toolbar");
                    return false;
                }else{
                    data.x = val;
                    IS_MOVE=true;
                }
                break;
            case "width":
                val = parseInt(val);
                if(Model.define.page.width <  data.x + val){
                    toobarErr(errEl, thisPos, "元素横向坐标加宽度不得超编辑器大小！");
                    that.focus();
                    IS_MOVE=false;
                    Utils.selectShape(id, false, "toolbar");
                    return false;
                }else{
                    if(Model.define.elements[id].name === "arrow" || Model.define.elements[id].name === "obstacle" || Model.define.elements[id].name === "myPlace" ){
                        data.h = val;
                    }
                    data.w = val;
                    IS_MOVE=true;
                }
                break;
            case "y":
                val = parseInt(val);
                if(Model.define.page.height < val + data.h){
                    toobarErr(errEl, thisPos, "元素纵向坐标加高度不得超编辑器大小！");
                    that.focus();
                    IS_MOVE=false;
                    Utils.selectShape(id, false, "toolbar");
                    return false;
                }else{
                    data.y = val;
                    IS_MOVE=true;
                }
                break;
            case "height":
                val = parseInt(val);
                if(Model.define.page.height < val + data.y){
                    toobarErr(errEl, thisPos, "元素纵向坐标加高度不得超编辑器大小！");
                    that.focus();
                    IS_MOVE=false;
                    Utils.selectShape(id, false, "toolbar");
                    return false;
                }else{
                    if(Model.define.elements[id].name === "arrow" || Model.define.elements[id].name === "obstacle" || Model.define.elements[id].name === "myPlace"){
                        data.w = val;
                    }
                    data.h = val;
                    IS_MOVE=true;
                }
                break;
        };
        Designer.painter.renderShape(Model.define.elements[id]);
        errEl.attr("data-lock", "false").hide();
        Utils.unselect();
        Utils.selectShape([id]);
    }
    //输入框获得焦点
    $(document).on("focus", ".toolbar-size input", function(e){
        $(document).on("click.toobarSize", function(e){
            if($(".toolbar-error").css("display") !== "none") return;
            var target = $(e.target);
            if(target.parents("#designer_header").length === 1 || target.attr("id") === "designer_header"){
                $(".toolbar-size input[data-type=width]").removeAttr("disabled");
                $(".toolbar-size input[data-type=height]").removeAttr("disabled");
                $(".toolbar-size input[data-type=x]").removeAttr("disabled");
                $(".toolbar-size input[data-type=y]").removeAttr("disabled");
                return false;
            }
            $(document).off("click.toobarSize");
            Utils.unselect();
        })
    });
    //点击回车键重置元素大小位移
    $(document).on("keyup", ".toolbar-size input", function(e){
        if(e.keyCode === 13){
            toolbarSet($(this), e);
        }
    });
    //输入框失去焦点重置元素大小位移
    $(document).on("blur", ".toolbar-size input", function(e){
        toolbarSet($(this), e);
    });
    //机器设置
    function sliders(elem){
        if($(elem).length !== 0){
            var div=document.createElement("div");
            div.className="fuChuang";
            $( elem+" .sliderBf" ).slider({
                range: "min",
                value: 32,
                min: 20,
                max: 100,
                slide: function( event, ui ){
                    Utils.unselect();
                    div.innerHTML=ui.value +"px";
                    cp_width=ui.value;
                    cp_size=parseFloat($(".cpNum").css("font-size"));
                    $(".text_cp").html(cp_size+"px");
                    $(elem+" .ui-slider-handle").empty().append(div);
                    var e=Model.define.elements;
                    var newElw=[];
                    for(ids in e){
                        if(e[ids].name === 'addComputer'){
                            var data = e[ids].props;//当前设置元素的位移宽高层级
                            newElw.push(e[ids]);
                            var nowEl=e[ids];
                            data.w = ui.value;
                            data.h = ui.value*22/32;
                            Designer.painter.renderShape(nowEl);
                        }
                    }
                    $(document).unbind("mouseup.huakuai").bind("mouseup.huakuai", function () {
                        $(document).unbind("mousemove.huakuai").unbind("mouseup.huakuai");
                        Model.updateMulti(newElw);
                    });
                }
            });
            div.innerHTML=$( elem+" .sliderBf" ).slider("value") +"px";
            $(elem+" .ui-slider-handle").empty().append(div);
        }
    }
    sliders(".cpWSetSize");
    //机器字号设置
    $("#cpFontSize").on("click", function(){
        // cp_width=$(" .sliderBf" ).slider("value");
        $("#font_cps").css({left: $(this).position().left+ "px",top:parseFloat($(".header").height())+"px"}).toggle();
        $("#font_cps li .ico_selected").remove();
        $("#font_cps li[ac="+ parseInt($(".cpNum").css("font-size"))+"]").prepend('<div class="ico ico_selected"></div>');
        setTimeout(function(){
            $(document).on("click.fontS", function(e){
                //console.log(e.target.nodeName);
                if($(e.target).attr("id") === "cpFontSize" || $(e.target).parents("#cpFontSize").length === 1){
                    return;
                }
                $("#font_cps").hide();
                $(document).off("click.fontS");
            });
        }, 10);
    });
    $(document).on("click", "#font_cps li", function(){
        // cp_width=$(" .sliderBf" ).slider("value");
        var k = parseFloat($(this).text());
        cp_size= k;
        $(".text_cp").html(cp_size+"px");
        $("#font_cps li .ico_selected").remove();
        $(this).prepend('<div class="ico ico_selected"></div>');
        $("#font_cps").hide();
        var e=Model.define.elements;
        var newElw=[];
        for(ids in e){
            if(e[ids].name === 'addComputer'){
                var s = e[ids].fontStyle;//当前设置元素的字号
                newElw.push(e[ids]);
                var nowEl=e[ids];
                s.size=k;
                Designer.painter.renderShape(nowEl);
            }
        }
        Model.updateMulti(newElw);
    });
    //批量添加机器
    $(document).on('input propertychange',".setCp",function(){
        if(($(this).val() > 1000) || (/\D/.test($(this).val()))  ){
            if($(this).val() > 1000){
                $(this).val(1000);
            }else{
                $(this).val("");
            }
        }
    });
    $(".saveCP").click(function(){
        var $leftCp=$(".cpTc .leftSetCp");
        var $rightCp=$(".cpTc .rightSetCp");
        var $cpErr=$(".cpTc .cperrorDiv");
        var $cpName=$(".cpTc .setCpName");
        if($leftCp.val().trim() === "" || $rightCp.val().trim() === "" ){
            $cpErr.html("计算机数字范围不能为空");
        }else{
            if(parseInt($leftCp.val()) > parseInt($rightCp.val()) ){
                $cpErr.html("起始数不能大于结尾数");
            }else{
                var cpName=$cpName.val().trim();
                var firstN=parseInt($leftCp.val().trim());
                var lastN=parseInt($rightCp.val().trim());
                var len=$leftCp.val().trim().length;
                var n=(lastN-firstN)+1;
                var oldNum=$(".cpNum"),oldArr=[];
                for(var f=0;f<oldNum.length;f++){
                    oldArr.push($(oldNum[f]).val().toLowerCase());
                }
                var cpSi=cp_size;
                MessageSource.beginBatch();
                var j=-1,jy=0;
                for(var iN=0;iN<n;iN++){
                    var type = "addComputer";
                    var valNums=String(firstN+iN);
                    var ns=valNums.length;
                    function zRNum(ns){
                        var strN='';
                        if(ns<len){
                            for(var i=0;i<(len-ns);i++){
                                strN+="0";
                            }
                        }
                        return strN;
                    }
                    valNums=cpName+zRNum(ns)+valNums;
                    if($.inArray(valNums.toLowerCase(),oldArr) > -1){
                        continue;
                    }
                    if(j+2 > parseInt(Model.define.page.width/46)){
                        j=0;
                        jy++;
                    }else{
                        j++;
                    }
                    var v={
                        x:30+(j*44),
                        y:20+(jy*34)
                    }
                    var newEl=d(type, v.x,v.y);
                    var q = $("#" + newEl.id);
                    function addCp(){
                        for(_i in Model.define.elements){
                            if(Model.define.elements[_i].name === "addComputer"){
                                var props=Model.define.elements[_i].props;
                                return props;
                            }
                        }
                    }
                    var _props= addCp() !== undefined ? addCp():{ w: 32, h: 22};
                    newEl.props.w=_props.w;
                    newEl.props.h=_props.h;
                    newEl.fontStyle.size=cpSi;
                    cp_width=_props.w;
                    $(" .sliderBf" ).slider("value",cp_width) ;
                    $(" .fuChuang" ).html(cp_width+"px") ;
                    $(".text_cp").html(cpSi+"px");
                    q.css({
                        width:_props.w,
                        height:_props.h,
                        left: v.x  + "px",
                        top: v.y  + "px",
                        "z-index": Model.orderList.length
                    });
                    newEl.props.x = v.x.restoreScale() ;
                    newEl.props.y = v.y.restoreScale() ;
                    var tempIndex = 2;
                    tempIndex += Model.orderList.length;
                    q.css({
                        left: (newEl.props.x).toScale() + "px",
                        top: (newEl.props.y).toScale() + "px",
                        "z-index": tempIndex
                    });
                    newEl.props.zindex = tempIndex;
                    newEl.componentsObj.computerNum=valNums;
                    q.attr("class", "shape_box ").css("z-index", newEl.props.zindex);
                    q.find(".cpNum").val(newEl.componentsObj.computerNum);
                    q.find(".cpNum").css("font-size",cpSi);
                    q.find(".addPcDiv").attr("data-val",newEl.componentsObj.computerNum);
                    Designer.events.push("created", newEl);
                    Model.add(newEl);
                    Designer.op.resetState();
                }
                MessageSource.commit();
                $(this).parents(".tcBg").hide(0);
                $(".cpTc input").val("");
                $cpErr.html("重复机器号(字母不区分大小)系统将跳过（不重复生成）");
                function d(o, q, p) {
                    var l = Schema.shapes[o];
                    var i = q.restoreScale() - l.props.w / 2;
                    var r = p.restoreScale() - l.props.h / 2;
                    var m = Model.create(o, i, r);
                    Designer.painter.renderShape(m);
                    return m;
                }
            }
        }
    });
    $(".qxCP").click(function(){
        $(this).parents(".tcBg").hide(0);
        $(".cpTc input").val("");
        $(".cpTc .cperrorDiv").html("重复机器号(字母不区分大小)系统将跳过（不重复生成）");
    });
    //批量修改机器号
    var cp_si;
    $(".setComputerBtn").click(function(e){
        e.preventDefault();
       $(".cpSetBg").show();
        cp_si=cp_size;
        // cp_width=$(" .sliderBf" ).slider("value");
    });
    $(document).on('input propertychange',".leftSetCp2",function(){
        var $leftCp1=$(".cpSetTc .leftSetCp1");
        var $rightCp1=$(".cpSetTc .rightSetCp1");
        var firstN1=parseInt($leftCp1.val().trim());
        var lastN1=parseInt($rightCp1.val().trim());
        var lens=parseInt(lastN1 - firstN1);
        if($leftCp1.val() !== "" && $rightCp1 !== ""  && $(this).val() !== "" ){
            var numBers= parseInt($(this).val())+lens >1000 ? 1000 : parseInt($(this).val())+lens;
            $(".cpSetTc .rightSetCp2").val(numBers);
        }
    });
    $(".saveCPSet").click(function(e){
        e.preventDefault();
        var $leftCp1=$(".cpSetTc .leftSetCp1");
        var $rightCp1=$(".cpSetTc .rightSetCp1");
        var $cpErr1=$(".cpSetTc .cperrorDiv1");
        var $cpName1=$(".cpSetTc .setCpName1");
        var $leftCp2=$(".cpSetTc .leftSetCp2");
        var $rightCp2=$(".cpSetTc .rightSetCp2");
        var $cpErr2=$(".cpSetTc .cperrorDiv2");
        var $cpName2=$(".cpSetTc .setCpName2");
        var cpName1=$cpName1.val().trim();
        var firstN1=parseInt($leftCp1.val().trim());
        var lastN1=parseInt($rightCp1.val().trim());
        var cpName2=$cpName2.val().trim();
        var firstN2=parseInt($leftCp2.val().trim());
        var lastN2=parseInt($rightCp2.val().trim());
       if($leftCp1.val().trim() === "" || $rightCp1.val().trim() === "" ){
           $cpErr1.show().html("原计算机名数字范围不能为空");
       }else{
           if(parseInt($leftCp1.val()) > parseInt($rightCp1.val()) ){
               $cpErr1.show().html("原计算机名数字范围起始数不能大于结尾数");
           }else{
               $cpErr1.hide();
               if($leftCp2.val().trim() === "" || $rightCp2.val().trim() === "" ){
                   $cpErr2.html("调整计算机名数字范围不能为空");
               }else{
                   if(parseInt($leftCp2.val()) > parseInt($rightCp2.val()) ){
                       $cpErr2.html("调整计算机名数字范围起始数不能大于结尾数");
                   }else{
                       if((firstN1 - lastN1) !== (firstN2 - lastN2)){
                           $cpErr2.html("调整计算机名数字范围个数有误");
                       }else{
                           $(" .sliderBf" ).slider("value",cp_width) ;
                           $(" .fuChuang" ).html(cp_width+"px") ;
                           $(".text_cp").html(cp_si+"px");
                           cp_size=cp_si;
                           var len1=$leftCp1.val().trim().length;
                           var len2=$leftCp2.val().trim().length;
                           var n=(lastN2-firstN2)+1;
                           var  i = [],cNumber= 0,setNumber=0;
                           function zRNum(ns,len){
                               var strN='';
                               if(ns<len){
                                   for(var i=0;i<(len-ns);i++){
                                       strN+="0";
                                   }
                               }
                               return strN;
                           }
                           var oldNum=$(".cpNum"),oldArr=[];
                           for(var f=0;f<oldNum.length;f++){
                               oldArr.push($(oldNum[f]).val().toLowerCase());
                           }
                           for(var iN=0;iN<n;iN++){
                               var valNums1=String(firstN1+iN);
                               var ns1=valNums1.length;
                               valNums1=cpName1+zRNum(ns1,len1)+valNums1;
                               var q;
                               if(oldNum.length !== 0){
                                   for(var f=0;f<oldNum.length;f++){
                                       var oldVal=$(oldNum[f]).val();
                                       if(oldVal.toLowerCase() === valNums1.toLowerCase()){
                                           cNumber++;
                                           q = $(oldNum[f]).parents(".shape_box");
                                           var valNums2=String(firstN2+iN);
                                           var ns2=valNums2.length;
                                           valNums2=cpName2+zRNum(ns2,len2)+valNums2;
                                           if($.inArray(valNums2.toLowerCase(),oldArr) > -1){
                                               continue;
                                           }
                                           if(q !== undefined){
                                               var id= q.attr("id");
                                               var newEl=Model.define.elements[id];
                                               newEl.componentsObj.computerNum=valNums2;
                                               setNumber++;
                                               i.push(newEl);
                                               q.find(".cpNum").val(valNums2);
                                               q.find(".addPcDiv").attr("data-val",valNums2);
                                               Designer.painter.renderShape(newEl);
                                           }
                                       }
                                   }
                               }
                           }
                           if(cNumber > 0 && setNumber > 0){
                               $(this).parents(".tcBg").hide(0);
                               $(".cpSetTc input").val("");
                               $cpErr1.hide();
                               $cpErr2.html("重复机器号(字母不区分大小)系统将跳过（不重复生成）");
                               Model.updateMulti(i);
                           }else{
                               if(cNumber === 0){
                                   $cpErr1.show().html("原计算机名不存在");
                                   $cpErr2.html("原计算机名不存在不做调整");
                               }else  if(setNumber === 0){
                                   $cpErr2.html("重复机器号(字母不区分大小)不做调整");
                               }
                           }

                       }
                   }
               }
           }
       }
    });
    $(".qxCPSet,.cpSetTc .tcClosed").click(function(){
        $(this).parents(".tcBg").hide(0);
        $(".cpSetTc input").val("");
        $(".cpSetTc .cperrorDiv1").hide();
        $(".cpSetTc .cperrorDiv").html("重复机器号(字母不区分大小)系统将跳过（不重复生成）");
    });
    $(document).on('input propertychange',"#CPNum input", function(){
        var thisPos = $(this).position();//当前元素位移
        var val = $(this).val().trim();//清空输入内容的容格
        var errEl = $(".toolbar-error");//错误提示框
        var id = errEl.attr("data-id");//错误提示的id
        var data = Model.define.elements[id].props;//当前设置元素的位移宽高层级
        var cpn=Model.define.elements[id].componentsObj;
        if(thisPos.left < 100){
            thisPos = $(this).next().position();
        }
        $(".computer-top-nav").hide();
        thisPos.left += 2;
        thisPos.top += 13;
        cpn.computerNum= val;
        $("#"+id+" .cpNum").val(cpn.computerNum);
        $("#"+id+" .shape_canvas").attr("data-val",cpn.computerNum);
        Designer.setLineStyle({computerNum:val}, $(".computer-top-nav").attr("data-id"));
        errEl.attr("data-lock", "false").hide();
        Utils.unselect();
        Utils.selectShape([id]);
    });
    $(document).on("keyup", "#CPNum input", function(e){
        if(e.keyCode === 13){
            $(this).blur();
        }
    });
    $(document).on("dblclick",".cpNum",function(){
        OPERATION = true;
        $(this).css("cursor","text");
        if($(this).val() === ""){
            $(this).val("");
        }else{
            $(this).val($(this).val());
        }
        $(this).removeAttr("readonly");
    });
    var valcp='';
    $(document).on('change',".cpNum", function(e){
        valcp=$(this).val();
        $("#CPNum input").val(valcp);
        $(this).parents(" .shape_canvas").attr("data-val",valcp);
        Model.define.elements[$(this).parents(".shape_box").attr('id')].componentsObj.computerNum = valcp;
    });
    $(document).on("keyup", ".cpNum", function(e){
        $("#CPNum input").val(valcp);
        if(e.keyCode === 13){
            $(this).blur();
        }
    });
    $(document).on("blur", ".cpNum", function(e){
        OPERATION = false;
        $(this).css("cursor","default");
        $(this).attr("readonly","readonly");
    });

    //恢复 (Ctrl+Y) 禁用
    $("#bar_redo").addClass("disabled");
    //撤销 (Ctrl+Z) 禁用
    $("#bar_undo").addClass("disabled");
    //对齐方式 禁用
    $("#component-align").addClass("disabled");
    //更多对齐方式显示隐藏
    $("#component-align").on("click", function(){
        if($(this).hasClass("disabled")){
            $(".top-align-list1").hide();
            return;
        }
        $(".top-align-list1").css({left: $(this).position().left+ "px",top:parseFloat($(".header").height())+"px"}).toggle();
        $(document).on("click.hideAlign", function(e){
            if($(e.target).attr("id") === "component-align" || $(e.target).parents("#component-align").length === 1){
                return;
            }
            $(".top-align-list1").hide();
            $(document).off("click.hideAlign");
        });
    });
    // 换肤设置
    $(".component-set").on("click",function(e){
        $(document).off("click.setHf");
        var navEl = $(".computer-top-nav");
        navEl.show();
        IS_SELECT=true;
        var style = {
            x: (e.pageX + navEl.width() - e.offsetX + 3),
            y: (e.pageY - e.offsetY)
        }
        if($(document).width() -312< style.x){
            style.x -= 312;
        }
        if($(document).height() - 218 < style.y){
            style.y -= 218;
        }
        $("#setHf li .ico_selected").remove();
        $("#setHf li").removeClass("action");
        $("#setHf li[ac="+ Model.define.elements[navEl.attr("data-id")].componentsObj.comsvg +"]").addClass("action").prepend('<div class="ico ico_selected"></div>');
        $("#setHf li .ico_selected").css({top:"inherit",left:"inherit",right:"4px",bottom:"4px"}).parent().addClass("action");
        $("#setHf>div").hide();
        $("#setHf>div>ul[class*='"+Model.define.elements[navEl.attr("data-id")].name+"UlList']").parent().show();
        $("#setHf").css({
            left: style.x + "px",
            top: style.y + "px"
        }).show();
        setTimeout(function(){
            $(document).on("click.setHf", function(e){
                if($(e.target).attr("id") === "setHf" || $(e.target).parents("#setHf").length === 1){
                    return;
                }
                $("#setHf").hide();
                $(document).off("click.setHf");
            });
        }, 10);
    });
    $(document).on("click", "#setHf li", function(){
        var  k= $(this).find(".liDiv ").html();
        var ac=$(this).attr("ac");
        Designer.setLineStyle({comsvg: ac,comsvgHtml:k}, $(".computer-top-nav").attr("data-id"));
        $("#setHf li").removeClass("action");
        $("#setHf li .ico_selected").remove();
        $(this).addClass("action").prepend('<div class="ico ico_selected"></div>');
        $("#setHf").hide();
        $(document).off("click.setHf");
    });
    // 字体设置
    $(".component-setFontW").on("click",function(e){
        $(document).off("click.fontf");
        var navEl = $(".computer-top-nav");
        navEl.show();

        IS_SELECT=true;
        // var style = {
        //     x: (e.pageX + navEl.width() - e.offsetX + 3),
        //     y: (e.pageY - e.offsetY)
        // }
        var style = {
            x: navEl[0].offsetLeft+navEl.width()+8,
            y: navEl[0].offsetTop
        }
        // if($(document).width() - 101 < style.x){
        //     style.x -= 130;
        // }
        // if($(document).height() - 130 < style.y){
        //     style.y -= 130;
        // }
        $("#font_f li .ico_selected").remove();
        $("#font_f li[ac="+ Model.define.elements[navEl.attr("data-id")].fontStyle.fontFamily +"]").prepend('<div class="ico ico_selected"></div>');
        $("#font_f").css({
            left: style.x + "px",
            top: style.y + "px"
        }).show();
        setTimeout(function(){
            $(document).on("click.fontf", function(e){
                if($(e.target).attr("id") === "font_f" || $(e.target).parents("#font_f").length === 1){
                    return;
                }
                $("#font_f").hide();
                $(document).off("click.fontf");
            });
        }, 10);
    });
    $(document).on("click", "#font_f li", function(){
        var k = $(this).text();
        Designer.setLineStyle({fontFamily: k}, $(".computer-top-nav").attr("data-id"));
        $("#font_f li .ico_selected").remove();
        $(this).prepend('<div class="ico ico_selected"></div>');
        $("#font_f").hide();
        $(document).off("click.font_f");
    });
    // 字号设置
    $(".component-setFontS").on("click",function(e){
        $(document).off("click.fonts");
        var navEl = $(".computer-top-nav");
        navEl.show();
        IS_SELECT=true;
        // var style = {
        //     x: (e.pageX + navEl.width() - e.offsetX + 3),
        //     y: (e.pageY - e.offsetY)
        // }
        // if($(document).width() - 101 < style.x){
        //     style.x -= 130;
        // }
        // if($(document).height() - 320 < style.y){
        //     style.y -= 320;
        // }
        
        var style = {
            x: navEl[0].offsetLeft+navEl.width()+8,
            y: navEl[0].offsetTop + 34
        }
        $("#font_s li .ico_selected").remove();
        $("#font_s li[ac="+ Model.define.elements[navEl.attr("data-id")].fontStyle.size +"]").prepend('<div class="ico ico_selected"></div>');
        $("#font_s").css({
            left: style.x + "px",
            top: style.y + "px"
        }).show();
        setTimeout(function(){
            $(document).on("click.fonts", function(e){
                if($(e.target).attr("id") === "font_s" || $(e.target).parents("#font_s").length === 1){
                    return;
                }
                $("#font_s").hide();
                $(document).off("click.fonts");
            });
        }, 10);
    });
    $(document).on("click", "#font_s li", function(){
        var k = parseInt($(this).text());
        Designer.setLineStyle({size: k}, $(".computer-top-nav").attr("data-id"));
        $("#font_s li .ico_selected").remove();
        $(this).prepend('<div class="ico ico_selected"></div>');
    });
    //编辑文字
    $(document).on("dblclick",".textDiv",function(){
        OPERATION = true;
        $(this).css("cursor","text");
        var vl=$(this).val();
        if(vl === "请输入文字"){
            $(this).val("");
        }
        $(this).removeAttr("readonly");
    });
    $(document).on('input propertychange',".textDiv", function(){
        var val=$(this).val();
        Designer.setLineStyle({textAer: val}, $(".computer-top-nav").attr("data-id"));
    });
    $(document).on("blur", ".textDiv", function(e){
        OPERATION = false;
        $(this).css("cursor","default");
        var vl=$(this).val();
        if(vl === ""){
            $(this).val("请输入文字");
        }
        $(this).attr("readonly","readonly");
    });
    //线条宽度设置
    $(".component-linewidth").on("click", function(e){
        $(document).off("click.hidelinewidth");
        var navEl = $(".computer-top-nav");
        navEl.show();
        IS_SELECT=true;
        var style = {
            x: (e.pageX + navEl.width() - e.offsetX + 3),
            y: (e.pageY - e.offsetY)
        }
        if($(document).width() - 180 < style.x){
            style.x -= 180;
        }
        if($(document).height() - 440 < style.y){
            style.y -= 440;
        }
        $("#line_width_list li .ico_selected").remove();
        $("#line_width_list li[ac="+ Model.define.elements[navEl.attr("data-id")].lineStyle.lineWidth +"]").prepend('<div class="ico ico_selected"></div>');
        $("#line_width_list").css({
            left: style.x + "px",
            top: style.y + "px"
        }).show();
        setTimeout(function(){
            $(document).on("click.hidelinewidth", function(e){
                if($(e.target).attr("id") === "line_width_list" || $(e.target).parents("#line_width_list").length === 1){
                    return;
                }
                $("#line_width_list").hide();
                $(document).off("click.hidelinewidth");
            });
        }, 10);
    });
    $(document).on("click", "#line_width_list li", function(){
        var k = parseInt($(this).text());
        Designer.setLineStyle({lineWidth: k}, $(".computer-top-nav").attr("data-id"));
        $("#line_width_list li .ico_selected").remove();
        $(this).prepend('<div class="ico ico_selected"></div>');
    });
    //颜色设置
    $(".component-color").on("click", function(e){
        $(document).off("click.hidecolor");
        var navEl = $(".computer-top-nav");
        navEl.show();
        IS_SELECT=true;
        // var style = {
        //     x: (e.pageX + navEl.width() - e.offsetX + 3),
        //     y: (e.pageY - e.offsetY)
        // }
        // if($(document).width() - 151 < style.x){
        //     style.x -= 183;
        // }
        // if($(document).height() - 150 < style.y){
        //     style.y -= 150;
        // }
        
        var style = {
            x: navEl[0].offsetLeft + navEl.width()+8,
            y: navEl[0].offsetTop + 68
        }
        $("#color_picker .color_items .selected").removeClass("selected");
        var forEl = $("#color_picker .color_items div");
        var idNow=Model.define.elements[navEl.attr("data-id")];
        var nowval = (idNow.name === "transverseline" || idNow.name === 'longstring') ? idNow.lineStyle.lineColor : idNow.fontStyle.color;
        for(var i = 0, len = forEl.length; i < len; i++){
            var forElBgColor = forEl.eq(i).css("background-color"),rgbbg = forElBgColor.split("(")[1].split(")")[0];
            if(rgbbg === nowval){
                forEl.eq(i).addClass("selected");
            }
        }
        $("#color_picker").css({left: style.x + "px",top: style.y + "px"}).show();
        setTimeout(function(){
            $(document).on("click.hidecolor", function(e){
                if($(e.target).attr("id") === "color_picker" || $(e.target).parents("#color_picker").length === 1){
                    return;
                }
                $("#color_picker").hide();
                $(document).off("click.hidecolor");
            })
        }, 10);
    });
    $(document).on("click", "#color_picker .color_items div", function(){
        var val = $(this).css("background-color"), bgColor = val.split("(")[1].split(")")[0];
        Designer.setLineStyle({ lineColor : bgColor }, $(".computer-top-nav").attr("data-id"));
        $("#color_picker .color_items .selected").removeClass("selected");
        $(this).addClass("selected");
    });

    //渐变设置 
    $(".component-setColor").on("click", function(e){
        console.log('aaa');
        // $(document).off("click.hidesetcolor");
        var navEl = $(".computer-top-nav");
        navEl.show();
        IS_SELECT=true;
        
        var style = {
            x: navEl[0].offsetLeft + navEl.width()+8,
            y: navEl[0].offsetTop + 102
        }
        var forEl = $("#background_picker");
        var idNow=Model.define.elements[navEl.attr("data-id")];
        
        $("#background_picker").css({left: style.x + "px",top: style.y + "px"}).show();
        
        //渐变
        var textId = $(".computer-top-nav").attr("data-id");
        
        $('#background_picker').ClassyGradient({                                
            gradient: '#00ffff 0%,#008900 30%,#f00044 70%,#0042d2 100%',
            onChange: function(stringGradient, cssGradient) {
                $('#'+textId).find('textarea').css({
                    'background': cssGradient.split(');')[0].split('background:')[1]+')',
                    'background-size': '100% 100%',
                    '-webkit-background-clip': 'text',
                    'color': 'transparent'
                });
            }
        }); 
    });

    //对齐设置
    $(document).on("click",".top-align-list li", function(e){
        var type = $(this).attr("act");
        switch(type){
            case "left":
                Designer.clipboard.leftalign();
                break;
            case "center":
                Designer.clipboard.centeralign();
                break;
            case "right":
                Designer.clipboard.rightalign();
                break;
            case "top":
                Designer.clipboard.topalign();
                break;
            case "bottom":
                Designer.clipboard.bottomalign();
                break;
            case "alCenter":
                Designer.clipboard.alCenter();
                break;
            case "distributionlevel":
                Designer.clipboard.distributionlevelalign();
                break;
            case "distributionvertical":
                Designer.clipboard.distributionverticalalign();
                break;
        }
    });
    //设置背景
    $("#setWallpaperBtn").click(function(){
        $(".wallPaperDiv").slideDown(100);
        bj = $(".wallPaperList .action").data("bj");
        newBgImg=$(".wallPaperList .action").find("img").attr("src");
    });
    $(".wallPaperList").on("click","li",function(){
        if(!!!$(this).hasClass("addWallPaper")){
            $(this).addClass("action").siblings().removeClass("action");
            newBgImg=$(this).find("img").attr("src");
            $("#canvas_container").css("background-image","url("+newBgImg+")");
        }
    });
    $(".tcQuDing").click(function(){
        IS_BJ=true;
        $(this).parents(".wallPaperDiv").slideUp(100);
        Designer.setPageStyle({ backgroundImage:newBgImg}, true);
        Model.define.page.backgroundImage=newBgImg;
    });
    $(".tcQuXiao").click(function(){
        $(this).parents(".wallPaperDiv").slideUp(100,function(){
            $(".wallPaperList [data-bj = '"+bj+"']").addClass("action").siblings().removeClass("action");
        });
        $("#canvas_container").css("background-image","url("+Model.define.page.backgroundImage+")");
    });
});

$(document)
    .on("click", ".component-del", function () { //删除
        var id = $(this).parents(".computer-top-nav").attr("data-id");
        if(Model.define.elements[id]){
            console.log(Model.define.elements[id].title);
            $("#panel_flow>div[shapename='"+Model.define.elements[id].computerType+"'] .title").html(Model.define.elements[id].title);
            Model.define.elements[id].nodel = false;
        }else{
            return false;
        }
        Designer.op.removeShape(Model.define.elements[id]);
        cpWSetShow();
        if(IS_SELECT) {
            $(".computer-top-nav").hide();
        }
    }).on("mouseenter", ".computer-top-nav .hand", function(e){
        var pos = $(this).offset(), text = $(this).attr("data-tit");
        $(".tsdialog-nav-tit").text(text).css({
            display: "block",
            left: pos.left + $(this).width()+10,
            top: pos.top
        });
    }).on("mouseleave", ".computer-top-nav .hand", function(){
        $(".tsdialog-nav-tit").hide();
    });

//元素title提示
var pageTitle = {
    time: 5000,
    cache: "",
    show: function (text, position, id) {
        var $el = $(".otitle");
        if(pageTitle.cache === id || $el.attr("data-lock") === id){
            return;
        }
        pageTitle.cache = id;

        $el.attr("data-lock", id);
        
        if(position.y>Model.define.page.height-182){
            $el.text(text).css({
                left: position.x,
                top: position.y-82,
                "z-index": Model.orderList.length + 2,
                display: "block"
            });
        }else {
            $el.text(text).css({
                left: position.x,
                top: position.y,
                "z-index": Model.orderList.length + 2,
                display: "block"
            });
        }

    },
    cleartimeout: function(){
        pageTitle.cache = "";
    },
    setinterval: function(){
        setInterval(function(){
            $(".otitle").hide();
            pageTitle.cleartimeout();
        }, pageTitle.time);
    },
    hide: function(id){
        pageTitle.cache = "";
        var $el = $(".otitle");
        $el.hide();
        if(id){
            $el.attr("data-lock", id);
        }else{
            $el.attr("data-lock", "");
        }
    }
}

$(document).on("mousemove", ".panel_box", function (s) {
    var nowpanel = $(this),nowtype = nowpanel.attr("shapename");
    if(MAXLENELEMENT[nowtype] > 0){
        var len = 0;
        for(var i in Model.define.elements){
            if(Model.define.elements[i].name === nowtype){
                len++;
            }
        }
        if(len >= MAXLENELEMENT[nowtype]){
            $(this).css("cursor","not-allowed");
            $(this).find(".title").html("该元素已添加");
        }else{
            pageTitle.hide();
            $(this).css("cursor","default");
        }
    }else if(MAXLENELEMENT[nowtype] < 0){
        pageTitle.hide();
    }
});
